/*  description :JS 访问Android原生功能插件
 *  author :hetanhong
 *  create :2014-6-17
 *  update : 2014-8-28

 */
window.isMobile = {
    Android: function () {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function () {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function () {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function () {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    any: function () {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
};

document.addEventListener("touchmove", function (event) {
    event.preventDefault();
}, false);

// 页面跳转 ，封装pc端和Android版本
window.openView = function (URL, callback) {
    if (isMobile.Android()) {
        window.plugins.getIntent.openView([URL]);
    } else {
        window.location = URL;
    }
};
// 页面跳转 ，封装pc端和Android版本 ，与window.openView不同之处在于Android版本  ，分别打开不同的activity
window.openViewB = function (URL, callback) {
	window.location = URL;
    /*if (isMobile.Android()) {
        window.plugins.getIntent.openViewB([URL]);
    } else {
        window.location = URL;
    }*/
};
window.openViewC = function (URL, callback) {
	window.location = URL;
	/*if (isMobile.Android()) {
        window.plugins.getIntent.openViewC([URL]);
    } else {
        window.location = URL;
    }*/
};
window.openViewG = function (URL, callback) {
	window.location = URL;
    /*if (isMobile.Android()) {
        window.plugins.getIntent.openViewG([URL]);
    } else {
        window.location = URL;
    }*/
};
// 退回上一页 ，封装pc端和Android
window.closeView = function (backURL) {
	if(backURL){
		window.location = backURL;
	}else{
		history.go(-1);
	}
    /*if (isMobile.Android()) {
        window.plugins.getIntent.closeView([]);
    }
    else {
        history.go(-1);
    }*/
};
// 获取文件系统 ，需要进行Android文件系统读写时 调用
var Ready = function () {
    // 获得文件系统 ，并创建名为  ‘download_test’ 的文件夹，应用附件将被下载到此文件夹中
    window.appRootDirName = "download_test";
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {

        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, fail);
    }

    function fail() {
        console.log("failed to get filesystem");
    }

    function gotFS(fileSystem) {
        console.log("filesystem got");
        window.fileSystem = fileSystem;
        window.Ready = true;
        fileSystem.root.getDirectory(window.appRootDirName, {
            create: true,
            exclusive: false
        }, dirReady, fail);
    }

    function dirReady(entry) {
        window.appRootDir = entry;
    }
};
// 下载并打开附件
// url 服务器上附件路径
// 保存的fileName 文件名
var openF = function (url, fileName,domId) {
	if (isMobile.Android()){
		navigator.notification.activityStart("政府OA系统", "正在下载文件");
	}
    url = encodeURI(url);
    if (window.fileSystem) {
        var fileSystem = window.fileSystem;
        var fileTransfer = new FileTransfer();
        var len = url.split(".").length;
        var filename = fileSystem.root.nativeURL + "download_test/" + fileName.split(".")[0] + "." + url.split(".")[len - 1];
        fileTransfer.download(url,
            filename,
            function (entry) { 
        		// download success
				if(domId){
					//edit by xushuang,显示保存修改
					document.getElementById(domId).style.display="inline";
				}
				if (isMobile.Android()){
					navigator.notification.activityStop();
				}
                var path = fileSystem.root.nativeURL + entry.fullPath; //文件绝对路径
                window.plugins.getIntent.hide();
                if (path.split(".")[1] === "apk" || path.split(".")[1] === "APK") {
                	//文件为 apk ，立即安装
                    window.plugins.getIntent.install([path], function () {}, function () {});
                }else {
                    window.open(path, "_system");
                }
            },
            function (error) {
            	if (isMobile.Android()){
					navigator.notification.activityStop();
				}
            	window.plugins.getIntent.hide();
            	Alert(fileError[error.code]);//提示错误信息
            }
        );
    }else {
    	// 重新获取文件系统
        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0,gotFS,fail);
        function gotFS(fileSystem) {
            console.log("filesystem got");
            window.fileSystem = fileSystem;
            window.Ready = true;
            fileSystem.root.getDirectory(window.appRootDirName, {
                create: true,
                exclusive: false
            }, function () {
                var fileTransfer = new FileTransfer();
                var filename = fileSystem.root.nativeURL + "download_test/" + fileName.split(".")[0] + "." + url.split(".")[len - 1];
                fileTransfer.download(url,
                    filename,
                    function (entry) { 
                		// download success
	                	if (isMobile.Android()){
	    					navigator.notification.activityStop();
	    				}
	                	var path = fileSystem.root.nativeURL + entry.fullPath;
                        if (path.split(".")[1] === "apk" || path.split(".")[1] === "APK") {
                            window.plugins.getIntent.install([path], function () {}, function () {});
                        }else {
                            window.open(path, "_system");
                        }
                    },
                    function (error) {
                    	if (isMobile.Android()){
        					navigator.notification.activityStop();
        				}
                        window.plugins.getIntent.hide();
                        Alert(fileError[error.code]);
                    }
                );
            }, function () {});
        }
        function fail(error){
        	if (isMobile.Android()){
				navigator.notification.activityStop();
			}
            Alert('error'+error);
            console.log('error：'+error);
        }

    }
    return;
};
// 下载头像
window.downLoad = function (url, fileName, suc) {
    url = encodeURI(url);
  //  url = url.replace(serverURL, "http://111.53.1.34:80/")

    if (window.fileSystem) {
        var fileSystem = window.fileSystem;
        var fileTransfer = new FileTransfer();
        var len = url.split(".").length;
        var filename = fileSystem.root.nativeURL + "download_test/PIC/" + fileName.split(".")[0] + "." + url.split(".")[len - 1];
        fileTransfer.download(url,
            filename,
            function (entry) { // download success
                var path = fileSystem.root.nativeURL + entry.fullPath; //文件绝对路径
                suc(path);
            },
            function (error) {
            }
        );
    }
    else {
        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, function () {
        });
        function gotFS(fileSystem) {
            window.fileSystem = fileSystem;
            window.Ready = true;
            fileSystem.root.getDirectory(window.appRootDirName, {
                create: true,
                exclusive: false
            }, function () {
                var fileTransfer = new FileTransfer();
                var filename = fileSystem.root.nativeURL + "download_test/PIC/" + fileName.split(".")[0] + "." + url.split(".")[len - 1];
                fileTransfer.download(url,
                    filename,
                    function (entry) { // download success

                        var path = fileSystem.root.nativeURL + entry.fullPath;
                        suc(path);
                    },
                    function (error) {
                    }
                );
            }, function () {
            });
        }
    }
}

var uploadFile = function (url,fileName,params) {
    url = encodeURI(url);
	//上传进度
    function showUploadingProgress(progressEvt) {
        if (progressEvt.lengthComputable) {
            navigator.notification.progressValue(Math.round(( progressEvt.loaded / progressEvt.total ) * 100));
        }
    }
    if (window.fileSystem) {
        var fileSystem = window.fileSystem;
        var fileTransfer = new FileTransfer();
        fileTransfer.onprogress = showUploadingProgress;
        navigator.notification.progressStart("", "当前上传进度");
		var fullFileUrl = fileSystem.root.nativeURL + "download_test/" + fileName;//上传的文件
		var options = new FileUploadOptions();//上传参数
        options.fileKey = "upLoadFile";
        options.fileName = fileName;  
        options.mimeType = "doc"; 
		options.params = params;
        fileTransfer.upload(
			fullFileUrl,
			url,
            function (entry) { // upload success
                window.plugins.getIntent.hide();
                navigator.notification.progressStop();
                 Prompt("上传成功!", 2000);
            },
            function (error) { // upload failed
                window.plugins.getIntent.hide();
                navigator.notification.progressStop();
               Prompt(fileError[error.code], 2000);
            },
			options
        );
    }
	// 重新获取文件系统
    else {
        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, function () {
        });
        function gotFS(fileSystem) {
            console.log("filesystem got");
            window.fileSystem = fileSystem;
            window.Ready = true;
            fileSystem.root.getDirectory(window.appRootDirName, {
                create: true,
                exclusive: false
            }, function () {
				var fileTransfer = new FileTransfer();
				fileTransfer.onprogress = showUploadingProgress;
				navigator.notification.progressStart("", "当前上传进度");
				var fullFileUrl = fileSystem.root.nativeURL + "download_test/" + fileName;//上传的文件
				var options = new FileUploadOptions();//上传参数
				options.fileKey = "upLoadFile";
				options.fileName = fileName;  
				options.mimeType = "doc"; 
				options.params = params;
				fileTransfer.upload(
					fullFileUrl,
					url,
					function (entry) { // upload success
						window.plugins.getIntent.hide();
						navigator.notification.progressStop();
						 Prompt("上传成功!", 2000);
					},
					function (error) { // upload failed
						window.plugins.getIntent.hide();
						navigator.notification.progressStop();
						Prompt(fileError[error.code], 2000);
					},
					options
				);
            }, function () {
            });
		}
	}
	return;
}